package cn.example.zjgsu.service.Impl;

import cn.example.zjgsu.dao.*;
import cn.example.zjgsu.exception.MyException;
import cn.example.zjgsu.pojo.Collection;
import cn.example.zjgsu.pojo.FocusUser;
import cn.example.zjgsu.pojo.FoodRecord;
import cn.example.zjgsu.pojo.User;
import cn.example.zjgsu.pojo.result.*;
import cn.example.zjgsu.service.MyPageServer;
import cn.example.zjgsu.util.SplitPictures;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: miaopeihan
 * @date: 2020-03-25  15:48
 */
@Service
public class MyPageServerImpl implements MyPageServer {

    @Autowired
    UserMapper userMapper;

    @Autowired
    FoodRecordMapper foodRecordMapper;

    @Autowired
    CollectionMapper collectionMapper;

    @Autowired
    FocusUserMapper focusUserMapper;

    @Autowired
    CityMapper cityMapper;

    @Autowired
    CommentMapper commentMapper;

    SplitPictures splitPictures = new SplitPictures();

    @Override
    public List<ResultRank> getNationalRank(String account) {
        List<ResultRank>result=new ArrayList<ResultRank>();
        List<User>users=userMapper.selectNationalRank();
        User myUser=userMapper.selectByPrimaryKey(account);
        int myRank=1001,cnt=0,last=-1,rank=0;
        for(User user:users){
            ResultRank resultRank = new ResultRank();
            cnt++;
            if(last!=user.getScore()) rank=cnt;
            resultRank.setRank(rank);
            resultRank.setUserId(user.getAcount());
            resultRank.setHeadportrait(user.getHeadportrait());
            resultRank.setName(user.getName());
            resultRank.setScore(user.getScore());
            result.add(resultRank);
            if(user.getAcount().equals(account)) myRank=rank;
            last=user.getScore();
        }
        ResultRank resultRank = new ResultRank();
        resultRank.setRank(myRank);
        resultRank.setUserId(myUser.getAcount());
        resultRank.setHeadportrait(myUser.getHeadportrait());
        resultRank.setName(myUser.getName());
        resultRank.setScore(myUser.getScore());
        result.add(resultRank);
        return result;
    }

    @Override
    public List<ResultRank> getCityRank(String account) {
        User myUser=userMapper.selectByPrimaryKey(account);
        List<ResultRank>result=new ArrayList<ResultRank>();
        List<User>users=userMapper.selectCityRank(myUser.getCityid());
        int myRank=1001,cnt=0,last=-1,rank=0;
        for(User user:users){
            ResultRank resultRank = new ResultRank();
            cnt++;
            if(last!=user.getScore()) rank=cnt;
            resultRank.setRank(rank);
            resultRank.setUserId(user.getAcount());
            resultRank.setHeadportrait(user.getHeadportrait());
            resultRank.setName(user.getName());
            resultRank.setScore(user.getScore());
            result.add(resultRank);
            if(user.getAcount().equals(account)) myRank=rank;
            last=user.getScore();
        }
        ResultRank resultRank = new ResultRank();
        resultRank.setRank(myRank);
        resultRank.setUserId(myUser.getAcount());
        resultRank.setHeadportrait(myUser.getHeadportrait());
        resultRank.setName(myUser.getName());
        resultRank.setScore(myUser.getScore());
        result.add(resultRank);
        return result;
    }

    @Override
    public ResultPersonInfo getPersonInfo(String userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        ResultPersonInfo resultPersonInfo = new ResultPersonInfo();
        List<FoodRecord> foodRecords = foodRecordMapper.selectByUserId(userId);
        List<ResultFoodRecord> resultFoodRecords = new ArrayList<ResultFoodRecord>();
        resultPersonInfo.setUserId(userId);
        resultPersonInfo.setHeadportrait(user.getHeadportrait());
        resultPersonInfo.setName(user.getName());
        resultPersonInfo.setAge(user.getAge());
        resultPersonInfo.setSex(user.getSex());
        resultPersonInfo.setFansNumber(user.getFansnumber());
        resultPersonInfo.setFocusNumber(user.getAttention());
        for(FoodRecord foodRecord:foodRecords){
            ResultFoodRecord resultFoodRecord = new ResultFoodRecord(foodRecord);
            resultFoodRecord.setPictures(splitPictures.getSplitPictures(foodRecord.getPictures()));
            resultFoodRecords.add(resultFoodRecord);
        }
        resultPersonInfo.setResultFoodRecords(resultFoodRecords);
        return resultPersonInfo;
    }

    @Override
    public List<ResultMainFoodRecord> getFavorites(String userId) {
        List<Collection>collections = collectionMapper.selectByUserId(userId);
        List<ResultMainFoodRecord>result = new ArrayList<>();
        for(Collection cs:collections){
            int foodRecordId=cs.getFoodrecordis();
            FoodRecord foodRecord = foodRecordMapper.selectByPrimaryKey(foodRecordId);
            ResultFoodRecord resultFoodRecord = new ResultFoodRecord(foodRecord);
            resultFoodRecord.setPictures(splitPictures.getSplitPictures(foodRecord.getPictures()));
            User user = userMapper.selectByPrimaryKey(foodRecord.getUserid());

            ResultMainFoodRecord resultMainFoodRecord = new ResultMainFoodRecord();
            resultMainFoodRecord.setUserId(user.getAcount());
            resultMainFoodRecord.setName(user.getName());
            resultMainFoodRecord.setHeadportrait(user.getHeadportrait());
            resultMainFoodRecord.setResultFoodRecord(resultFoodRecord);

            result.add(resultMainFoodRecord);
        }
        return result;
    }

    @Override
    public List<ResultFocusInfo> getFocusList(String userId) {
        List<String> accounts = focusUserMapper.getFocus(userId);
        List<ResultFocusInfo> result = new ArrayList<ResultFocusInfo>();
        for(String account:accounts){
            User user = userMapper.selectByPrimaryKey(account);
            ResultFocusInfo resultFocusInfo = new ResultFocusInfo(user);
            String cityName = cityMapper.selectByPrimaryKey(user.getCityid()).getName();
            resultFocusInfo.setCityName(cityName);
            result.add(resultFocusInfo);
        }
        return result;
    }

    @Override
    public boolean collectFoodRecord(String userId, int foodRecordId) {
        Collection collection = new Collection();
        collection.setFoodrecordis(foodRecordId);
        collection.setUserid(userId);
        int state = collectionMapper.insert(collection);
        if(state>0) return true;
        else return false;
    }

    @Override
    public boolean disCollectFoodRecord(String userId, int foodRecordId) {
        Collection collection = new Collection();
        collection.setFoodrecordis(foodRecordId);
        collection.setUserid(userId);
        collectionMapper.deleteByCollection(collection);
        return true;
    }

    @Override
    public boolean focusPerson(String myAccount, String focusAccount) {
        User myUser = userMapper.selectByPrimaryKey(myAccount);
        myUser.setAttention(myUser.getAttention()+1);
        userMapper.updateByPrimaryKey(myUser);
        User focusUser = userMapper.selectByPrimaryKey(focusAccount);
        focusUser.setFansnumber(focusUser.getFansnumber()+1);
        userMapper.updateByPrimaryKey(focusUser);
        FocusUser record = new FocusUser();
        record.setAcount(myAccount);
        record.setFocusacount(focusAccount);
        focusUserMapper.insert(record);
        return true;
    }

    @Override
    public boolean disFocusPerson(String myAccount, String focusAccount) {
        User myUser = userMapper.selectByPrimaryKey(myAccount);
        myUser.setAttention(myUser.getAttention()-1);
        userMapper.updateByPrimaryKey(myUser);
        User focusUser = userMapper.selectByPrimaryKey(focusAccount);
        focusUser.setFansnumber(focusUser.getFansnumber()-1);
        userMapper.updateByPrimaryKey(focusUser);
        FocusUser record = new FocusUser();
        record.setAcount(myAccount);
        record.setFocusacount(focusAccount);
        focusUserMapper.delete(record);
        return true;
    }

    @Override
    public List<ResultMFR> getCollectionFoodRecord(String userid) throws MyException {
        List<Collection>collections = collectionMapper.selectByUserId(userid);
        if (collections.size()==0){
            throw new MyException("你还没有收藏食记哦,快去收藏一篇吧");
        }
        List<ResultMFR> resultMFRS=new ArrayList<>();
        for (Collection collection : collections) {
            ResultMFR briefFoodRecord= foodRecordMapper.getBriefFoodRecordById(collection.getFoodrecordis());
            briefFoodRecord.setCommentnumber(commentMapper.getCommentNumberOfFD(briefFoodRecord.getId()));
            resultMFRS.add(briefFoodRecord);
        }
        return resultMFRS;
    }

    @Override
    public String fileUpload(MultipartFile file, HttpServletRequest request, String sex,String age,String acount) throws IOException {
        //获取文件名 : file.getOriginalFilename();    
        String uploadFileName = file.getOriginalFilename();
        //如果文件名为空，直接回到首页！  
        if ("".equals(uploadFileName)) {
            return "redirect:/index.html";
        }
        System.out.println("上传文件名 : " + uploadFileName);
        //上传路径保存设置  
        String path = ResourceUtils.getURL("classpath:").getPath()+"static/file/";
        //如果路径不存在，创建一个  
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        System.out.println("上传文件保存地址：" + realPath);
        InputStream is = file.getInputStream();
        //文件输入流  
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); //文件输出流
        //读取写出  
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
            os.flush();
        }
        os.close();
        is.close();
        String productName="http://10.21.234.73:8080/user/"+uploadFileName;
        User user = userMapper.selectByPrimaryKey(acount);
        user.setHeadportrait(productName);
        user.setSex(sex);
        user.setAge(age);
        userMapper.updateByPrimaryKey(user);
        return "redirect:/index.html";
    }
}
